<template>
  <!-- 创建否定关键词投放 -->
  <div class="choose-product-w">
    <div class="head">商品投放</div>
    <div class="choose-product-con flex">
      <div class="choose-list">
        <a-tabs default-active-key="2">
          <a-tab-pane key="2" title="商品">
            <a-input-group :disabled="isDisabled" style="margin-bottom: 10px">
              <a-select v-model="bidType" style="width: 120px" size="small" @change="defaultBid = null">
                <a-option value="1" label="默认竞价" />
                <a-option value="2" label="自定义竞价" />
              </a-select>
              <a-input-number v-if="bidType == '1'" disabled size="small" style="width: 200px" :placeholder="(defaultTargetingBid || '') + ' 直接应用'">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
              <a-input-number v-else size="small" style="width: 200px" v-model="defaultBid" placeholder="">
                <template #append>
                  <a-button size="mini">{{ currency }}</a-button>
                </template>
              </a-input-number>
            </a-input-group>
            <div class="flex-c" style="margin-bottom: 10px">
              <span>匹配类型：</span>
              <a-checkbox-group :disabled="isDisabled" :min="1" v-model="productTypes">
                <a-checkbox value="ASIN_SAME_AS" :disabled="productTypes.length === 1 && productTypes[0] === 'ASIN_SAME_AS'">精准</a-checkbox>
                <a-checkbox value="ASIN_EXPANDED_FROM" :disabled="productTypes.length === 1 && productTypes[0] === 'ASIN_EXPANDED_FROM'">扩展</a-checkbox>
              </a-checkbox-group>
            </div>
            <a-textarea v-model="asinVal" :disabled="isDisabled" placeholder="输入ASIN，一行一个" allow-clear style="height: 240px" />
            <div class="flex-c-sb">
              <p>不得包含特殊字符，如@、#、*、$、/等</p>
              <a-button size="mini" type="primary" @click="addProductByKeyword" v-if="!isDisabled">添加</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="checked-list">
        <div class="flex-c" style="margin-bottom: 10px">
          <p style="margin-right: 10px">已添加{{ editSpCampaignInfo.productTargetingInfos.length }}个商品</p>
          <p>(最多可添加1000个)</p>
        </div>
        <a-table size="mini" class="table-normal-line" :pagination="false" :scroll="{ x: '400', y: '320px' }" :data="editSpCampaignInfo.productTargetingInfos">
          <template #columns>
            <a-table-column title="品类和商品">
              <template #cell="{ record }">
                <p>
                  <span>{{ MatchType[record.matchType] }}商品：</span>
                  <span>{{ record.asin }}</span>
                </p>
              </template>
            </a-table-column>
            <a-table-column title="竞价">
              <template #title>
                <p>
                  <span>竞价</span>
                  <span class="warningColor">*</span>
                  <span>({{ currency }})</span>
                </p>
              </template>
              <template #cell="{ record }">
                <a-input-number size="mini" style="width: 120px" v-model="record.bid" placeholder="" allow-clear />
              </template>
            </a-table-column>
            <a-table-column :width="80">
              <template #title>
                <p class="highlight cursor" @click="editSpCampaignInfo.productTargetingInfos = []" v-if="!isDisabled">删除所有</p>
              </template>
              <template #cell="{ rowIndex }">
                <icon-close-circle class="cursor" style="font-size: 16px" @click="deleteProduct(rowIndex)" v-if="!isDisabled" />
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { MatchType, DraftFinishStep } from '../../types'
  import { marketPlaceList } from '@/utils/globalData'
  const props = defineProps({
    darftInfo: {
      type: Object,
      default: () => {},
    },
    defaultTargetingBid: {
      type: [String, Number],
    },
    shop: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(() => {
    editSpCampaignInfo.value.productTargetingInfos = props.darftInfo?.productTargetingInfos || []
  })
  const productTypes = ref(['ASIN_SAME_AS'])
  const editSpCampaignInfo = ref<any>({
    productTargetingInfos: [],
  })
  const asinVal = ref()
  const bidType = ref('1')
  const defaultBid = ref()
  const currency = computed(() => {
    let marketplaceId = props.shop?.marketplaceId
    return marketplaceId ? marketPlaceList[marketplaceId]?.currency : 'USD'
  })
  // 根据当前流程节点判断是否可编辑
  let isDisabled = computed(() => {
    let handlerFlow = props.darftInfo?.handlerFlow || 'INIT'
    let level = DraftFinishStep[handlerFlow]
    return Number(level) > 4 ? true : false
  })
  // 添加Asin
  function addKeyword(list: Array<any>) {
    // 去重
    list.forEach((el: any) => {
      let _index = editSpCampaignInfo.value.productTargetingInfos.findIndex((item: any) => item.asin == el.asin && item.matchType == el.matchType)
      if (_index == -1 && editSpCampaignInfo.value.productTargetingInfos.length < 1000) {
        editSpCampaignInfo.value.productTargetingInfos.push(el)
      }
    })
  }
  // 输入ASIN添加
  async function addProductByKeyword() {
    if (!asinVal.value) {
      Message.error('请输入ASIN')
      return
    }
    const reg = new RegExp('[~!@#$^&*=《》?！@#￥&*{}【】‘；：。，、？]')
    if (reg.test(asinVal.value)) {
      Message.error('不得包含特殊字符，如@、#、*、$、/等')
      return
    }
    let bid = bidType.value === '1' ? props.defaultTargetingBid : defaultBid.value
    let asins = asinVal.value.split('\n')
    let list: Array<any> = []
    asins.forEach((val: string) => {
      let newVal = val?.trim()
      if (newVal) {
        productTypes.value.forEach((type: string) => {
          list.push({
            asin: newVal,
            matchType: type,
            bid: bid,
          })
        })
      }
    })
    addKeyword(list)
  }

  // 刪除产品
  function deleteProduct(i: number) {
    editSpCampaignInfo.value.productTargetingInfos.splice(i, 1)
  }
  // 校验信息
  async function validateData() {
    let arrs = editSpCampaignInfo.value.productTargetingInfos
    let noBid = arrs.some((el: any) => !(el.bid === 0 || el.bid))
    if (noBid) {
      Message.error('商品投放竞价必填')
      return false
    }
    return true
  }
  // 设置需要创建的数据
  function setCreateData() {
    return {
      productTargetingInfos: editSpCampaignInfo.value.productTargetingInfos,
      productCategoryTargetingType: 1,
    }
  }
  defineExpose({ validateData, setCreateData })
</script>
<style lang="less" scoped>
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 20px;
  }
  .choose-product-w {
    border: 1px solid var(--color-border);
    .head {
      padding: 6px 20px;
      border-bottom: 1px solid var(--color-border);
    }
    :deep(.arco-tabs-pane) {
      padding: 10px 20px;
    }
    .choose-list {
      width: 50%;
      border-right: 1px solid var(--color-border);
      flex-shrink: 0;
    }
    .checked-list {
      padding: 10px 20px;
      overflow: hidden;
      flex: 1;
    }
    :deep(.arco-input-append) {
      padding: 0;
      .arco-btn {
        padding: 0 3px;
      }
    }
  }
</style>
